package com.example.testjava;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.widget.Toast;

import java.util.Date;
import java.util.Random;

public class MyService extends Service {

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    static final int MSG_SAY_HELLO = 1;
    static final int MSG_GET_MSG = 2;

    class IncomingHandler extends Handler {
        private Context applicationContext;
        Random _rand = new Random(System.nanoTime());

        IncomingHandler(Context context) {
            applicationContext = context.getApplicationContext();
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Toast.makeText(applicationContext, "hello!", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_GET_MSG:
                    if (msg.replyTo != null) {
                        Bundle replyBundle = new Bundle();
                        replyBundle.putString("name", "xiaoming");
                        replyBundle.putInt("age", _rand.nextInt(70));

                        Message message = Message.obtain();
                        message.setData(replyBundle);
                        try {
                            msg.replyTo.send(message);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    MyBinder _binder = new MyBinder();

    Messenger _Messenger = null;

    public MyService() {
        Log.i("service", "construct");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.i("service", "bind");
        // 进程内
        //return _binder;

        // 跨进程
        _Messenger = new Messenger(new IncomingHandler(this));
        return _Messenger.getBinder();
    }

    public Date getTime(){
        return new Date();
    }
}